package chat

import (
	"github.com/gorilla/websocket"
	"log"
)

type message struct {
	ID        int64  `json:"id"`
	Friendsid int64  `json:"friendsid"` // 发送人ID
	Content   string `json:"content"`
	Addtime   int64  `json:"addtime"`
	Receiveid int64  `json:"receiveid,omitempty"` //   接收人id
	Classify  int64  `json:"classify"`
}

type Client struct {
	Friendsid int64
	Conn      *websocket.Conn
	Sender    chan *message
}

// ReadMessage 读客户端消息
func (c *Client) ReadMessage() {
	defer func() {
		c.Conn.Close()
		delete(Clients, c.Friendsid)
	}()
	for {
		c.Conn.PongHandler()
		var msg message
		if err := c.Conn.ReadJSON(&msg); err != nil {
			c.Conn.Close()
			delete(Clients, c.Friendsid)
			break
		}

		msg.Friendsid = c.Friendsid
		// 系统消息
		if msg.Friendsid == 1 {
			chatMsgxitong <- &msg
			continue
		}
		// 单聊
		if msg.Receiveid > 0 {
			chatMsgChan <- &msg
			//fmt.Println(chatMsgChan)
			continue
		}
	}

}

// WriteMessage 回复客户端消息
func (c *Client) WriteMessage() {
	defer func() {
		c.Conn.Close()
		delete(Clients, c.Friendsid)
	}()
	for {
		select {
		case m, ok := <-c.Sender:
			if !ok {
				if err := c.Conn.WriteMessage(websocket.CloseMessage, []byte{}); err != nil {
					return
				}
				return
			}
			log.Printf("发送到到客户端的信息:%v", m)
			if err := c.Conn.WriteJSON(m); err != nil {
				return
			}
		}
	}
}
